package com.hf.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hf.dao.AddressDao;
import com.hf.entity.Myaddress;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@WebServlet("/address.do")
public class AddressServlet extends HttpServlet {
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		PrintWriter out = resp.getWriter();
		HttpSession session = req.getSession();
		String type = req.getParameter("type");
		int user_id = (int) session.getAttribute("user_id");
		AddressDao addressDao = new AddressDao();
		if("queryall".equals(type)){
			List<Myaddress> addresslist = addressDao.getAddressAll(user_id);
			req.setAttribute("addresslist",addresslist);
			req.getRequestDispatcher("personal_data/my_address.jsp").forward(req, resp);
		}else if("modify".equals(type)){
			
		}else if("add".equals(type)){
			Myaddress myaddress =  requstGetData(req);
			addressDao.insertAdd(myaddress);
			List<Myaddress> addresslist = addressDao.getAddressAll(user_id);
			JSONArray jsonarray = JSONArray.fromObject(addresslist);
			JSONObject json = new JSONObject();
			json.put("addresslist", jsonarray);
			json.put("code", '0');
			json.put("message", "添加成功");
			out.print(json.toString());
		}else if("delete".equals(type)){
			
		}
		
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
	
	private Myaddress requstGetData(HttpServletRequest req){
		HttpSession session = req.getSession();
		int user_id = (int) session.getAttribute("user_id");
		String consignee = req.getParameter("consignee");
		String region_province = req.getParameter("region_province");
		String region_city = req.getParameter("region_city");
		String region_area = req.getParameter("region_area");
		String detailed_add = req.getParameter("detailed_add");
		String zip_code = req.getParameter("zip_code");
		String address_telephone = req.getParameter("address_telephone");
		
		Myaddress myaddress = new Myaddress(user_id,consignee,region_province,region_city,
				region_area,detailed_add,zip_code,address_telephone);
		
		return myaddress;
	}
	
}
